/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.wx.handler;

import cn.ac.iie.di.wx.httpservice.HttpSender;
import cn.ac.iie.di.commons.httpserver.framework.handler.HandlerI;
import cn.ac.iie.di.commons.httpserver.framework.util.ParseRequestStream;
import cn.ac.iie.di.wx.common.RuntimeEnv;
import cn.ac.iie.di.wx.mongoservice.MongoHelper;
import cn.ac.iie.di.wx.vo.PicUrlVo;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Request;

/**
 *
 * @author Administrator
 */
public class WxPictureUrl_old implements HandlerI {

    static Logger logger = Logger.getLogger(WxPictureUrl_old.class.getName());

    @Override
    public void execute(Request pRequest, HttpServletRequest request, HttpServletResponse response) throws Exception {
        boolean flag = false;
        try {
            byte[] bytesContent = new byte[1024 * 2];
            int bytesReadIn = 0;
            ServletOutputStream out = response.getOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream(out);
            //查库获取图片url，进行拼接后发送response,http连接资源释放问题需要注意,批量查询
            String _idurlStr = ParseRequestStream.parseRequestStreamAsString(pRequest.getInputStream());
            logger.info(_idurlStr);
            HttpSender hs = new HttpSender();
            int count = 0;
            while (count <= 15) {
                if (RuntimeEnv.wxPictureUrlQueryLimit.get() < Integer.parseInt((String) RuntimeEnv.getParam(RuntimeEnv.WXPICQLIMIT))) {

                    logger.info(RuntimeEnv.wxPictureUrlQueryLimit.incrementAndGet());
                    flag = true;
                    String urlresult = hs.sendStringByUrl(_idurlStr, (String) RuntimeEnv.getParam(RuntimeEnv.wxPicQueryUrl));//json的字符串
//                    String urlresult = hs.sendStringByUrl("{\"cmd\":16,\"url\":\"" + urlStr + "\"}", "http://10.238.3.12:8080/cgi-bin/pa_cgi");//json的字符串
                    logger.info(urlresult);
//获取下载地址.可以直接下载，根据图片下载程序进行下载功能，有下载程序，下载完后才能返回mongoPicUrl,使用运行时参数类初始化一个下载的线程进行下载
                    if (!urlresult.equals("")) {
                        JSONObject urljSONObject = JSONObject.parseObject(urlresult);
                        String data = urljSONObject.getString("data");
                        if (!data.isEmpty()) {
                            try {
                                JSONObject dldurljSONObject = JSONObject.parseObject(data);
                                String download_url = dldurljSONObject.getString("download_url");
//                            URL picDldUrl = new URL(download_url.replace("10.177.138.34", "10.238.3.12"));
                                InputStream responseIn = org.apache.http.client.fluent.Request.Get(download_url.replace("10.177.138.34", "10.238.3.12"))
                                        .execute().returnContent().asStream();
                                while ((bytesReadIn = responseIn.read(bytesContent, 0, 1024 * 2)) > 0) {
                                    bos.write(bytesContent, 0, bytesReadIn);
                                }
                                bos.flush();
                                bos.close();

                            } catch (Exception ex) {
                                InputStream inputStream = new ByteArrayInputStream(("腾讯图片接口调用失败：" + "下载图片出错").getBytes("UTF-8"));
                                while ((bytesReadIn = inputStream.read(bytesContent, 0, 1024 * 2)) > 0) {
                                    bos.write(bytesContent, 0, bytesReadIn);
                                }
                                bos.flush();
                                logger.error("下载图片出错" + ex.getMessage(), ex);
                                bos.close();
                            }
                        } else {
                            //发送未知错误返回 15:33

                            String errorinfo = urljSONObject.getString("errorinfo");
                            logger.info("未知错误信息：" + errorinfo);
                            InputStream inputStream = new ByteArrayInputStream(("腾讯图片接口调用失败：" + errorinfo).getBytes("UTF-8"));
                            while ((bytesReadIn = inputStream.read(bytesContent, 0, 1024 * 2)) > 0) {
                                bos.write(bytesContent, 0, bytesReadIn);
                            }
                            bos.flush();
                            bos.close();
                        }

                    } else {
                        //连接超时的返回
                        logger.info("访问超时");
                        InputStream inputStream = new ByteArrayInputStream("腾讯图片接口调用失败：访问超时".getBytes("UTF-8"));
                        while ((bytesReadIn = inputStream.read(bytesContent, 0, 1024 * 2)) > 0) {
                            bos.write(bytesContent, 0, bytesReadIn);
                        }
                        bos.flush();
                        bos.close();
                    }
                    RuntimeEnv.wxPictureUrlQueryCount.incrementAndGet();
                    logger.info("success");
                    break;
                }
                if (count >= 15) {
                    logger.info("访问量超限");
                    InputStream inputStream = new ByteArrayInputStream("腾讯图片接口调用失败：访问量超限".getBytes("UTF-8"));
                    while ((bytesReadIn = inputStream.read(bytesContent, 0, 1024 * 2)) > 0) {
                        bos.write(bytesContent, 0, bytesReadIn);
                    }
                    bos.flush();
                    bos.close();
                    break;
                }
                ++count;
                Thread.sleep(100);
            }

        } catch (Exception e) {
            logger.error("Filedownload send out error\n" + e.getMessage(), e);
        } finally {
            if (flag) {
                RuntimeEnv.wxPictureUrlQueryLimit.decrementAndGet();
            }
        }
    }

    @Override
    public void init() throws Exception {
//        logger.info("init WxPictureUrl");
    }
}
